package com.example.mq.rocketmq.producer;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.selector.SelectMessageQueueByHash;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

/**
 * 使用 DefaultMQProducer 发送消息
 *
 * @author luowj12
 * @since 2021/5/14 15:18
 */

@Component
public class RoketMQProducer2 {

    /**
     * 同步发送
     * @param id
     * @throws MQClientException
     * @throws RemotingException
     * @throws InterruptedException
     * @throws MQBrokerException
     */
    public void syncSend(Integer id) throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
        //创建一个生产者
        DefaultMQProducer producer=new DefaultMQProducer("rmq-group");
        //设置NameServer地址
        producer.setNamesrvAddr("127.0.0.1:9876");
        //设置生产者实例名称
        producer.setInstanceName("provider");
        //启动生产者
        producer.start();
        //发送消息
        Message message = new Message("weksoft_topic","TagA",("测试内容").getBytes());
        producer.send(message,  new SelectMessageQueueByHash(),15L);
    }

    /**
     * 异步发送
     * @throws MQClientException
     * @throws RemotingException
     * @throws InterruptedException
     */
    public void asyncSend() throws MQClientException, RemotingException, InterruptedException {
        //Instantiate with a producer group name.
        DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
        // Specify name server addresses.
        producer.setNamesrvAddr("localhost:9876");
        //Launch the instance.
        producer.start();
        producer.setRetryTimesWhenSendAsyncFailed(0);
        for (int i = 0; i < 100; i++) {
            final int index = i;
            //Create a message instance, specifying topic, tag and message body.
            Message msg = new Message("weksoft_topic","TagA",("测试内容").getBytes());
            producer.send(msg, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.printf("%-10d OK %s %n", index,
                            sendResult.getMsgId());
                }
                @Override
                public void onException(Throwable e) {
                    System.out.printf("%-10d Exception %s %n", index, e);
                    e.printStackTrace();
                }
            });
        }
        //Shut down once the producer instance is not longer in use.
        producer.shutdown();
    }

}
